package vacuum.noSpam;

import java.util.HashMap;

public class StatsAnalyzer
{

	HashMap<Character, Float> frequencyTable;
	//private boolean verbose; //unused

	public StatsAnalyzer(boolean verbose, HashMap<Character, Float> freqTable)
	{
		//this.verbose = verbose; //unused
		this.frequencyTable = freqTable;
	}

	public float characterFrequency(String message){

		if(message.length() == 0)
			return 0;

		int min = Character.MAX_VALUE, max = 0;

		char[] chars = message.toLowerCase().toCharArray();

		//find min/max values
		for(char c : chars)
		{
			if(min > c)
				min = c;
			if(max < c)
				max = c;
		}

		int[] counts = new int[max - min + 1];

		for(char c : chars){
			counts[c - min]++;
		}

		float tot = chars.length; //float so that we don't have to cast in the for loop

		float allPercs = 0;

		for (int i = 0; i < counts.length; i++)
		{
			if(!frequencyTable.containsKey((Character)(char)(i + min)))
				continue;
			float desFreq = frequencyTable.get((Character)(char)(i + min));
			float realFreq = counts[i] / tot; //MUST be float division, not integer
			float percDiff = Math.abs((realFreq - desFreq) / desFreq);

			allPercs += percDiff;
		}

		return allPercs/frequencyTable.keySet().size();

	}

	public float wordSize(String message){
		/*message = message.toLowerCase();

		int spaces = 0;

		int letters = 0;

		//count letters
		for(char c : message.toCharArray()){
			if(c >= 'a' && c <= 'z')
				letters++;
			if(c == ' ')
				spaces++;
		}
		*/
		float letters = message.replaceAll(" ", "").length() / (float)message.split(" ").length;
		return (1/(float)letters)*((float)letters - 5)*((float)letters - 5);
	}

	public float compareMessages(Message m1, Message m2){
		int distance = computeLevenshteinDistance(m1.getValue(), m2.getValue());
		return distance / (float)Math.max(m1.getValue().length(), m2.getValue().length());
	}

	/**
	 * Source: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Java
	 */
	public static int computeLevenshteinDistance(CharSequence str1,
			CharSequence str2) {
		int[][] distance = new int[str1.length() + 1][str2.length() + 1];

		for (int i = 0; i <= str1.length(); i++)
			distance[i][0] = i;
		for (int j = 0; j <= str2.length(); j++)
			distance[0][j] = j;

		for (int i = 1; i <= str1.length(); i++)
			for (int j = 1; j <= str2.length(); j++)
				distance[i][j] = minimum(
						distance[i - 1][j] + 1,
						distance[i][j - 1] + 1,
						distance[i - 1][j - 1]
						                + ((str1.charAt(i - 1) == str2.charAt(j - 1)) ? 0
						                		: 1));

		return distance[str1.length()][str2.length()];
	}

	private static int minimum(int a, int b, int c) {
		return Math.min(Math.min(a, b), c);
	}
	
	
	//this is unused right now
//	private void log(String s){
//		if(verbose){
//			System.out.println("[NoSpam]->[StatsAnalyzer]" + s);
//		}
//	}

}
